<template>
  <px-dialog v-model="showModal" :title="`${area.name} 区域温湿度 SPC 趋势图`" width="80%" top="5vh" destroy-on-close @close="close">
    <div class="spc-content">
      <div class="area-buttons">
        <px-button v-for="a in areas" :key="a.name" :type="a.name === area.name ? 'primary' : ''" size="small" @click="selectArea(a)">
          {{ a.name }}
        </px-button>
      </div>

      <div class="time-controls">
        <px-date-picker v-model="startTime" type="datetime" placeholder="开始时间" style="width: 200px" />
        <span class="separator">至</span>
        <px-date-picker v-model="endTime" type="datetime" placeholder="结束时间" style="width: 200px" />
        <px-button type="primary" size="small" @click="queryData"> 查询 </px-button>
        <px-button size="small" @click="resetTime"> 重置 </px-button>
      </div>

      <div ref="chartContainer" class="spc-chart" />
    </div>
  </px-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from "vue";
import * as echarts from "echarts";
import type { ECharts } from "echarts";
import { useFabStore } from "@/store/modules/fabStore";
import { PxMessage } from "px-ui";

const props = defineProps({
  area: {
    type: Object,
    required: true
  },
  currentView: {
    type: String,
    default: "temperature"
  }
});

const emit = defineEmits(["area-change", "close"]);

const fabStore = useFabStore();
const areas = computed(() => fabStore.areas);
const showModal = ref(true);
const chartContainer = ref<HTMLElement | null>(null);
let chart: ECharts | null = null;

// 时间范围 - 默认最近4小时
const now = new Date();
const startTime = ref<Date>(new Date(now.getTime() - 4 * 60 * 60 * 1000));
const endTime = ref<Date>(now);

// 处理窗口resize
const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

// 初始化图表
onMounted(() => {
  nextTick(() => {
    if (chartContainer.value) {
      chart = echarts.init(chartContainer.value);
      updateChart();
      window.addEventListener("resize", handleResize);
    }
  });
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  if (chart) {
    chart.dispose();
  }
});

// 监听模态框显示状态
watch(
  () => showModal.value,
  val => {
    if (val) {
      nextTick(() => {
        handleResize();
      });
    }
  }
);

// 关闭模态框
const close = () => {
  emit("close");
};

// 选择区域
const selectArea = (newArea: any) => {
  emit("area-change", newArea);
  nextTick(() => {
    queryData();
  });
};

// 查询数据
const queryData = () => {
  if (!startTime.value || !endTime.value) {
    PxMessage.warning("请选择有效的时间范围");
    return;
  }

  if (startTime.value >= endTime.value) {
    PxMessage.warning("开始时间必须早于结束时间");
    return;
  }

  updateChart();
};

// 重置时间范围
const resetTime = () => {
  const now = new Date();
  startTime.value = new Date(now.getTime() - 4 * 60 * 60 * 1000);
  endTime.value = now;
  queryData();
};

// 更新图表
const updateChart = () => {
  if (!chart) return;
  const params = {
    startTime,
    endTime,
    ...props.area,
    currentView: props.currentView
  };
  console.log(params, "123213213213");
  // 模拟数据 - 实际应用中应从API获取
  const timeSpan = endTime.value.getTime() - startTime.value.getTime();
  const hours = timeSpan / (60 * 60 * 1000);
  const dataCount = Math.min(Math.max(Math.floor(hours * 6), 100)); // 每10分钟一个点，最多100个点

  const xData = [];
  const seriesData = [];

  for (let i = 0; i < dataCount; i++) {
    const time = new Date(startTime.value.getTime() + (timeSpan * i) / dataCount);
    xData.push(time.toLocaleTimeString());

    const baseValue = props.currentView === "temperature" ? props.area.valueNewTemp : props.area.valueNewHumidity;

    const value = baseValue + (Math.random() - 0.5) * (props.currentView === "temperature" ? 0.5 : 2);

    seriesData.push(value);
  }

  const option = {
    animation: false,
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        return `${params[0].axisValue}<br/>
          ${props.currentView === "temperature" ? "温度" : "湿度"}: ${params[0].data}${props.currentView === "temperature" ? "°C" : "%"}`;
      }
    },
    grid: {
      top: 30,
      right: 30,
      bottom: "10%",
      left: 50
    },
    xAxis: {
      type: "category",
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: "value",
      name: props.currentView === "temperature" ? "温度(°C)" : "湿度(%)",
      min: props.currentView === "temperature" ? 0 : 0,
      max: props.currentView === "temperature" ? 25 : 45
    },
    series: [
      {
        name: props.currentView === "temperature" ? "温度" : "湿度",
        type: "line",
        data: seriesData,
        smooth: true,
        lineStyle: {
          width: 2,
          color: props.currentView === "temperature" ? "#f56c6c" : "#409eff"
        },
        itemStyle: {
          color: props.currentView === "temperature" ? "#f56c6c" : "#409eff"
        },
        markLine: {
          silent: true,
          data:
            props.currentView === "temperature"
              ? [
                  { name: "上限", yAxis: 23.5, lineStyle: { color: "#f56c6c" } },
                  { name: "目标", yAxis: 22.5, lineStyle: { color: "#67c23a" } },
                  { name: "下限", yAxis: 21.5, lineStyle: { color: "#f56c6c" } }
                ]
              : [
                  { name: "上限", yAxis: 55, lineStyle: { color: "#f56c6c" } },
                  { name: "目标", yAxis: 50, lineStyle: { color: "#67c23a" } },
                  { name: "下限", yAxis: 45, lineStyle: { color: "#f56c6c" } }
                ]
        }
      }
    ]
  };

  chart.setOption(option);
  handleResize();
};

// 监听属性变化
watch(() => props.currentView, updateChart);
// watch(() => props.area, updateChart);
</script>

<style scoped lang="scss">
.spc-content {
  display: flex;
  flex-direction: column;
  height: 60vh;

  .area-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 16px;
  }

  .time-controls {
    display: flex;
    gap: 10px;
    align-items: center;
    margin-bottom: 16px;

    .separator {
      color: #666;
    }
  }

  .spc-chart {
    flex: 1;
    width: 100%;
  }
}
</style>
